<?php
namespace App\Services\MyAddr\MyAddr;

use App\Models\MyAddr\MyAddr;
use App\Services\Log\Log\LogLogic;
/**
 * @Author: 于婧雯
 * @Date:   2019-02-20 16:25:06
 * @Last Modified by:   ws
 * @Last Modified time: 2019-02-20
 */
class MyAddrLogic
{

    /*用户收货地址列表*/
    public function myAddrList($data): array
    {
        $_where['user_id'] = $data['user_id'];
        $_where['is_del'] = 0;
        $res = MyAddr::where($_where)
            ->paginate(10);
        return auto_return($res);
    }
    /*管理员收货地址列表（可搜用户id）*/
    public function adminMyAddrList($data): array
    {
        $_where['is_del'] = 0;
        $re = MyAddr::where($_where);
        if($data['keywords']){
            $re->where(function($query) use ($data){
                $query->where('user_id', '=', $data['keywords']);});
        }
        $res = $re->paginate(10);
        return auto_return($res);
    }

    //用户添加收货地址
    public function addMyAddr($data): array
    {
        unset($data['token']);
        $data['created_at'] = date('Y-m-d H:i:s',time());
        $data['updated_at'] = date('Y-m-d H:i:s',time());
        $res = MyAddr::insertGetId($data);
        return auto_return($res);
    }

    /*用户删除收货地址*/
    public function delMyAddr($data): array
    {
        //先查看该地址是否属于该用户
        unset($data['token']);
        $info = MyAddr::where($data)->select()->first();
        if (!$info) {
            return auto_return($info,'该收货地址不属于您');
        }
        $is_del['is_del'] = 1;
        $is_del['updated_at'] = date('Y-m-d H:i:s',time());
        $res =  MyAddr::where('id', '=', $data['id'])
            ->update($is_del);
        return auto_return($res, '删除收货地址成功', '删除收货地址失败');
    }

    /*用户修改收货地址*/
    public function altMyAddr($data): array
    {
        unset($data['token']);
        $_where['id'] = $data['id'];
        $_where['is_del'] = 0;
        $res =  MyAddr::where($_where)
                    ->update($data);
        return auto_return($res);
    }

    /*用户查看某条详情*/
    public function myAddrInfo($data): array
    {
        $_where['id'] = $data['id'];
        $_where['is_del'] = 0;
        $res = MyAddr::where($_where)->select()->first();
        return auto_return($res);

    }

    /*管理员删除收货地址*/
    public function adminDelMyAddr($data): array
    {
        //管理员删除收货地址
        $_where['id'] = $data['id'];
        $_where['is_del'] = 0;
        $_update['is_del'] = 1;
        $rst =  MyAddr::where($_where)
            ->update($_update);
        //添加管理员删除记录
        if ($rst) {
            // 写入日志
            $logData['id'] = session('userId');
            $logData['name'] = session('username');
            $logData['type'] = 3;
            $logData['record'] = "收货地址";
            (new LogLogic())->addLog($logData);
        }
        return auto_return($rst, '删除成功！', '删除失败！');
    }

}